<template>
  <formSearch
    :form-item="formItem"
    :form-data="formData"
    :add-btn="true"
    :reset-btn="true"
    @searchForm="searchForm"
    @clearForm="clearForm"
    @addData="showDialog('新增')"
  />
  <tableList
    :table-title="tableTitle"
    :table-data="tableData"
    :pageInfo="pageInfo"
    :showExpand="true"
    @changeStatus="changeStatus"
    @handleSizeChange="handleSizeChange"
    @handleCurrentChange="handleCurrentChange"
    @prevClick="prevClick"
    @nextClick="nextClick"
  >
    <template #btn="scope">
      <el-button type="text" @click="handleEdit(scope.slotval)">编辑</el-button>
    </template>

    <template #roleExpand="scope">
      <el-row
        v-for="(item1, i1) in scope.slotval.children"
        :key="item1.id"
        justify="center"
        :class="['bdBottom', i1 == 0 ? 'bdTop' : '', 'vcenter']"
      >
        <!-- 一级权限 -->
        <el-col :span="5">
          <el-tag closable @close="removeRightById(scope.slotval, item1.id)">
            {{ item1.authName }}
          </el-tag>
          <el-icon>
            <CaretRight />
          </el-icon>
        </el-col>
        <!-- 二级和三级权限 -->
        <el-col :span="19">
          <el-row
            v-for="(item2, i2) in item1.children"
            :key="item2.id"
            justify="center"
            :class="[i2 == 0 ? '' : 'bdTop', 'vcenter']"
          >
            <el-col :span="6">
              <el-tag
                type="success"
                closable
                @close="removeRightById(scope.slotval, item2.id)"
              >
                {{ item2.authName }}
              </el-tag>
              <el-icon>
                <CaretRight />
              </el-icon>
            </el-col>
            <el-col :span="18">
              <el-row
                v-for="(item3, i3) in item2.children"
                :key="item3.id"
                justify="center"
                :class="[i3 == 0 ? '' : 'bdTop', 'vcenter']"
              >
                <el-tag
                  type="warning"
                  closable
                  @close="removeRightById(scope.slotval, item3.id)"
                >
                  {{ item3.authName }}
                </el-tag>
                <el-icon>
                  <CaretRight />
                </el-icon>
              </el-row>
            </el-col>
          </el-row>
        </el-col>
      </el-row>
    </template>
  </tableList>

  <AddDialog
    :add-dialog="dialogOptions.dialogVisible"
    :title="dialogOptions.dialogTitle"
    :form-data="detailData"
    :right-list="rightList"
    :id="dataId"
    @clost-btn="closeBtn"
    @save-btn="saveBtn"
  >
  </AddDialog>
</template>

<script lang="ts" setup>
import { onMounted, ref, reactive } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import {formatTime} from "@/util/base/formatTime"
import init from "./option";
import AddDialog from "./components/AddDialog.vue";
import RoleServiceApi from "./api/roleServiceApi";
const roleServiceApi = new RoleServiceApi();

// 搜索组件
const formItem = init.formItem;
const formData = reactive({
  role: "",
});

// 表格和分页组件
const tableTitle = init.tableTitle;
const tableData = ref();
const pageInfo = reactive({
  currentPage: 1,
  pageSize: 10,
  totalCount: 30,
});

// 数据详情
const detailData = reactive({
  role: "",
  authority: [],
});
const dataId = ref<string>("");
const rightList = ref();
// 渲染成功
onMounted(() => {
  // console.log("执行了onMounted")
  getData();
  getRightList();
});

// 获取权限列表
const getRightList = async () => {
  const { data: data } = await roleServiceApi.getRightList();
  rightList.value = data;
};

// 获取列表数据
const getData = async () => {
  // console.log("执行了getData")
  // 封装请求参数
  let params: any = {
    role: formData.role,
    pageSize: pageInfo.pageSize,
    currentPage: pageInfo.currentPage,
  };

  let data:any = await roleServiceApi.getRoleList(params);
  let totalCount: number = data.totalCount;
  let tabledata: Array<Object> = data.data;
  tabledata.forEach((item:any) => {
    item.createTime = formatTime("YYYY年mm月dd日 HH:MM:SS", item.createTime);
  });
  tableData.value = tabledata;
  pageInfo.totalCount = totalCount;
};



const searchForm = () => {
  // console.log(formData);
  // console.log(pageInfo);
  getData();
};

// 重置搜索条件
const clearForm = () => {
  pageInfo.currentPage = 1;
  getData();
};

// -----------------新增编辑弹框------------------
// 组件传递参数
const dialogOptions = reactive({
  dialogVisible: false,
  dialogTitle: "",
});

// 点击新增/编辑按钮
const showDialog = (title: string) => {
  if(title=='新增') clearDetail()
  dialogOptions.dialogVisible = true;
  dialogOptions.dialogTitle = title;
};

const handleEdit = async (role: any) => {
  // 获取详情数据
  let detail:any = await getDetail(role._id);
  detailData.role = detail[0].role;
  dataId.value = role._id;

  // 获取权限id数组
  let arr:any = [];
  getDefaultKeys(role, arr);
  detailData.authority = arr;
  showDialog("编辑");
};

// 利用递归函数构建数组
const getDefaultKeys = (node:any, arr:any) => {
  if (!node.children || !node.children.length) {
    return arr.push(node.id);
  }
  node.children.forEach((item: any) => {
    getDefaultKeys(item, arr);
  });
};

// 获取详情信息
const getDetail = async (id: string) => {
  let res = await roleServiceApi.detail(id);
  return res.data;
};

// 清空详情页的数据
const clearDetail = () => {
  detailData.role = "";
  detailData.authority = [];
};

const closeBtn = () => {
  dialogOptions.dialogVisible = false;
  clearDetail();
  console.log('关闭按钮的时候调用------'+JSON.stringify(detailData))
};

const saveBtn = () => {
  dialogOptions.dialogVisible = false;
  formData.role = "";
  clearDetail();
  getData();
  console.log('保存按钮的时候调用------'+JSON.stringify(detailData))
};

// 改变状态
const changeStatus = async (roleId: string) => {
  // console.log("执行了changeStatus")
  let res = await roleServiceApi.changeStatus({ id: roleId });
  getData();
};

const handleSizeChange = (pageSize: number) => {
  // console.log("改变列表页面大小");
  pageInfo.pageSize = pageSize;
  getData();
};

const handleCurrentChange = (currentPage: number) => {
  // console.log("改变当前页面数字");
  pageInfo.currentPage = currentPage;
  getData();
};

const prevClick = (currentPage: number) => {
  pageInfo.currentPage = currentPage;
  getData();
};

const nextClick = (currentPage: number) => {
  pageInfo.currentPage = currentPage;
  getData();
};

// 删除权限
const removeRightById = async (role: any, rightId: string) => {
  // 弹出确认框
  const confirmResult = await ElMessageBox.confirm(
    "此操作将永远删除文件，是否继续？",
    "提示",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }
  ).catch(() => {
    ElMessage({
      type: "info",
      message: "取消了删除!",
    });
  });

  if (confirmResult == "confirm") {
    const { data: data } = await roleServiceApi.deleteRight(role._id, rightId);
    role.children = data;
    ElMessage({
      type: "success",
      message: "删除成功",
    });
  }
};
</script>

<style lang="scss" scoped>
.bdTop {
  border-top: 1px solid #eee;
}

.bdBottom {
  border-top: 1px solid #eee;
}

.vcenter {
  display: flex;
  align-items: center;
  text-align: center;
}
</style>
